//文件名：parseRequest.js
//将自定义parseRequest模块映射到parseReq入口，调用时直接调parseRequest(s1, s2)，而不是parseReq(s1,s2)
exports.parseRequest = parseReq;
//用于处理所有请求
function parseReq(s1, s2) {
    var fs = s1;
    var queryString = s2;
    //解析REST请求
    var restParse = function(response, pathName, queryStr) {
        //解析请求参数
        var reqStr = queryString.parse(queryStr);
        switch (pathName) {
            //简单实例，解析请求参数获取用户名并通过json数据返回
            case "/dojoTest/getUser":
                response.writeHead(200, { 'Content-Type': 'application/json;charset=utf-8' });
                var str = "{'errNum': 200,'retMsg': '请求成功','data':' 用户名是：" + reqStr.user + "'}";
                response.write(str);
                break;
                //简单实例：通过REST请求方式获取当前时间
            case "/dojoTest/getTime":
                response.writeHead(200, { 'Content-Type': 'application/json;charset=utf-8' });
                response.write("{'errNum': 200,'retMsg': '请求成功','data':' 当前时间：" + new Date().toLocaleString() + "'}");
                break;
                //如果没有对应的REST请求，报个501错误给浏览器
            default:
                response.writeHead(501, { 'Content-Type': 'application/json;charset=utf-8' });
                response.write('{"errNum": 501,"retMsg":"请求失败：该请求不存在","data":"null"}');

        }
        response.end();
    };
    //解析静态请求
    var fileParse = function(response, pathName, suffixStr) {
        //读取静态文件并生成流
        fs.readFile(pathName.substr(1), function(err, data) {
            if (err) {
                console.log(err);
                //HTTP 404 :页面不存在
                //没找到对应的静态文件怎么办，给个404错误
                response.writeHead(404, { 'Content-Type': 'text/html;charset=utf-8' });
                //响应文件流
                response.write("页面不存在！404");
                response.end();
            } else {
                //HTTP 200 : 成功
                if (suffixStr === ".css") {
                    //设置charset=utf-8防止乱码
                    response.writeHead(200, { 'Content-Type': 'text/css;charset=utf-8' });
                } else {
                    response.writeHead(200, { 'Content-Type': 'text/html;charset=utf-8' });
                }
                //响应文件流
                response.write(data.toString());
                response.end();
            }
        });
    }
    return {
        parseRest: restParse,
        parseFile: fileParse
    }
};
